package com.buaa.divinationmaster;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import android.widget.EditText;
import com.buaa.divinationmaster.algorithm.MeihuaAlgorithm;
import com.buaa.divinationmaster.utils.ScreenAdaptationUtil;
import com.buaa.divinationmaster.model.DivinationRecord;
import com.buaa.divinationmaster.manager.DatabaseManager;

import java.util.Calendar;

/**
 * 梅花易数占卜页面 - 完整商业级实现
 */
public class MeihuaActivity extends AppCompatActivity {
    
    private String selectedMethod = "time";
    private EditText etQuestion;
    private NumberPicker npUpperTrigram, npLowerTrigram, npChangingYao;
    
    // 完整的六十四卦名表
    private static final String[][] HEXAGRAM_NAMES = {
        {"乾为天", "天泽履", "天火同人", "天雷无妄", "天风姤", "天水讼", "天山遁", "天地否"},
        {"泽天夬", "兑为泽", "泽火革", "泽雷随", "泽风大过", "泽水困", "泽山咸", "泽地萃"},
        {"火天大有", "火泽睽", "离为火", "火雷噬嗑", "火风鼎", "火水未济", "火山旅", "火地晋"},
        {"雷天大壮", "雷泽归妹", "雷火丰", "震为雷", "雷风恒", "雷水解", "雷山小过", "雷地豫"},
        {"风天小畜", "风泽中孚", "风火家人", "风雷益", "巽为风", "风水涣", "风山渐", "风地观"},
        {"水天需", "水泽节", "水火既济", "水雷屯", "水风井", "坎为水", "水山蹇", "水地比"},
        {"山天大畜", "山泽损", "山火贲", "山雷颐", "山风蛊", "山水蒙", "艮为山", "山地剥"},
        {"地天泰", "地泽临", "地火明夷", "地雷复", "地风升", "地水师", "地山谦", "坤为地"}
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meihua);
        
        // 应用屏幕适配
        ScreenAdaptationUtil.applyScreenAdaptation(this);
        
        setupToolbar();
        initViews();
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("梅花易数");
        }
    }
    
    private void initViews() {
        etQuestion = findViewById(R.id.etQuestion);
        
        CardView cardTimeMethod = findViewById(R.id.cardTimeMethod);
        CardView cardNumberMethod = findViewById(R.id.cardNumberMethod);
        CardView cardRandomMethod = findViewById(R.id.cardRandomMethod);
        CardView cardNumberInput = findViewById(R.id.cardNumberInput);
        Button btnStartDivination = findViewById(R.id.btnStartDivination);
        
        npUpperTrigram = findViewById(R.id.npUpperTrigram);
        npLowerTrigram = findViewById(R.id.npLowerTrigram);
        npChangingYao = findViewById(R.id.npChangingYao);
        
        setupNumberPickers();
        setupClickListeners(cardTimeMethod, cardNumberMethod, cardRandomMethod, cardNumberInput, btnStartDivination);
        
        // 默认选择时间起卦
        selectMethod("time", cardTimeMethod, cardNumberMethod, cardRandomMethod, cardNumberInput);
    }
    
    private void setupNumberPickers() {
        if (npUpperTrigram != null) {
            npUpperTrigram.setMinValue(1);
            npUpperTrigram.setMaxValue(8);
            npUpperTrigram.setValue(1);
            String[] trigramNames = {"坤", "震", "坎", "兑", "艮", "离", "巽", "乾"};
            npUpperTrigram.setDisplayedValues(trigramNames);
            setNumberPickerTextColor(npUpperTrigram);
        }
        
        if (npLowerTrigram != null) {
            npLowerTrigram.setMinValue(1);
            npLowerTrigram.setMaxValue(8);
            npLowerTrigram.setValue(1);
            String[] trigramNames = {"坤", "震", "坎", "兑", "艮", "离", "巽", "乾"};
            npLowerTrigram.setDisplayedValues(trigramNames);
            setNumberPickerTextColor(npLowerTrigram);
        }
        
        if (npChangingYao != null) {
            npChangingYao.setMinValue(1);
            npChangingYao.setMaxValue(6);
            npChangingYao.setValue(1);
            setNumberPickerTextColor(npChangingYao);
        }
    }
    
    private void setNumberPickerTextColor(NumberPicker numberPicker) {
        try {
            // 通过反射设置NumberPicker的文字颜色为白色
            java.lang.reflect.Field selectorWheelPaintField = numberPicker.getClass()
                .getDeclaredField("mSelectorWheelPaint");
            selectorWheelPaintField.setAccessible(true);
            ((android.graphics.Paint) selectorWheelPaintField.get(numberPicker))
                .setColor(android.graphics.Color.WHITE);
            
            // 设置输入框文字颜色
            for (int i = 0; i < numberPicker.getChildCount(); i++) {
                android.view.View child = numberPicker.getChildAt(i);
                if (child instanceof android.widget.EditText) {
                    ((android.widget.EditText) child).setTextColor(android.graphics.Color.WHITE);
                }
            }
            
            numberPicker.invalidate();
        } catch (Exception e) {
            // 如果反射失败，静默处理
        }
    }
    
    private void randomizeNumberPickers() {
        java.util.Random random = new java.util.Random();
        
        if (npUpperTrigram != null) {
            npUpperTrigram.setValue(random.nextInt(8) + 1);
        }
        
        if (npLowerTrigram != null) {
            npLowerTrigram.setValue(random.nextInt(8) + 1);
        }
        
        if (npChangingYao != null) {
            npChangingYao.setValue(random.nextInt(6) + 1);
        }
    }
    
    private void setupClickListeners(CardView cardTimeMethod, CardView cardNumberMethod, 
                                   CardView cardRandomMethod, CardView cardNumberInput, Button btnStartDivination) {
        
        cardTimeMethod.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                selectMethod("time", cardTimeMethod, cardNumberMethod, cardRandomMethod, cardNumberInput);
            }
        });
        
        cardNumberMethod.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                selectMethod("number", cardTimeMethod, cardNumberMethod, cardRandomMethod, cardNumberInput);
            }
        });
        
        cardRandomMethod.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                selectMethod("random", cardTimeMethod, cardNumberMethod, cardRandomMethod, cardNumberInput);
            }
        });
        
        btnStartDivination.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String question = etQuestion.getText().toString().trim();
                if (question.isEmpty()) {
                    etQuestion.setError("请输入占卜问题");
                    etQuestion.requestFocus();
                    return;
                }
                startMeihuaDivination(question);
            }
        });
    }
    
    private void selectMethod(String method, CardView... cards) {
        selectedMethod = method;
        
        // 重置所有卡片状态
        for (CardView card : cards) {
            if (card.getId() == R.id.cardNumberInput) continue;
            card.setCardBackgroundColor(getColor(R.color.surface_dark));
            card.setAlpha(0.8f);
        }
        
        // 设置选中状态
        CardView selectedCard = null;
        switch (method) {
            case "time":
                selectedCard = findViewById(R.id.cardTimeMethod);
                findViewById(R.id.cardNumberInput).setVisibility(View.GONE);
                break;
            case "number":
                selectedCard = findViewById(R.id.cardNumberMethod);
                findViewById(R.id.cardNumberInput).setVisibility(View.VISIBLE);
                // 设置随机初始值
                randomizeNumberPickers();
                break;
            case "random":
                selectedCard = findViewById(R.id.cardRandomMethod);
                findViewById(R.id.cardNumberInput).setVisibility(View.GONE);
                break;
        }
        
        if (selectedCard != null) {
            selectedCard.setCardBackgroundColor(getColor(R.color.accent_gold_variant));
            selectedCard.setAlpha(1.0f);
        }
    }
    
    private void startMeihuaDivination(String question) {
        try {
            MeihuaResult result = null;
            
            switch (selectedMethod) {
                case "time":
                    result = performTimeMethod(question);
                    break;
                case "number":
                    result = performNumberMethod(question);
                    break;
                case "random":
                    result = performRandomMethod(question);
                    break;
            }
            
            if (result != null) {
                showMeihuaResult(result);
            }
            
        } catch (Exception e) {
            Toast.makeText(this, "占卜失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    // 结果类
    private static class MeihuaResult {
        String question, method, upperTrigram, lowerTrigram, hexagramName, interpretation;
        int changingYao;
        
        MeihuaResult(String question, String method, String upperTrigram, String lowerTrigram, 
                    int changingYao, String hexagramName, String interpretation) {
            this.question = question;
            this.method = method;
            this.upperTrigram = upperTrigram;
            this.lowerTrigram = lowerTrigram;
            this.changingYao = changingYao;
            this.hexagramName = hexagramName;
            this.interpretation = interpretation;
        }
    }
    
    private MeihuaResult performTimeMethod(String question) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        
        int upperNum = (year + month + day) % 8;
        if (upperNum == 0) upperNum = 8;
        
        int lowerNum = (year + month + day + hour) % 8;
        if (lowerNum == 0) lowerNum = 8;
        
        int changingYao = (year + month + day + hour) % 6;
        if (changingYao == 0) changingYao = 6;
        
        String[] trigrams = {"坤", "震", "坎", "兑", "艮", "离", "巽", "乾"};
        String upperTrigram = trigrams[upperNum - 1];
        String lowerTrigram = trigrams[lowerNum - 1];
        
        String hexagramName = getHexagramName(upperTrigram, lowerTrigram);
        String interpretation = generateInterpretation(question, "时间起卦", upperTrigram, lowerTrigram, changingYao, hexagramName);
        
        return new MeihuaResult(question, "时间起卦", upperTrigram, lowerTrigram, changingYao, hexagramName, interpretation);
    }
    
    private MeihuaResult performNumberMethod(String question) {
        int upperNum = npUpperTrigram != null ? npUpperTrigram.getValue() : 1;
        int lowerNum = npLowerTrigram != null ? npLowerTrigram.getValue() : 1;
        int changingYao = npChangingYao != null ? npChangingYao.getValue() : 1;
        
        String[] trigrams = {"坤", "震", "坎", "兑", "艮", "离", "巽", "乾"};
        String upperTrigram = trigrams[upperNum - 1];
        String lowerTrigram = trigrams[lowerNum - 1];
        
        String hexagramName = getHexagramName(upperTrigram, lowerTrigram);
        String interpretation = generateInterpretation(question, "数字起卦", upperTrigram, lowerTrigram, changingYao, hexagramName);
        
        return new MeihuaResult(question, "数字起卦", upperTrigram, lowerTrigram, changingYao, hexagramName, interpretation);
    }
    
    private MeihuaResult performRandomMethod(String question) {
        java.util.Random random = new java.util.Random();
        int upperNum = random.nextInt(8) + 1;
        int lowerNum = random.nextInt(8) + 1;
        int changingYao = random.nextInt(6) + 1;
        
        String[] trigrams = {"坤", "震", "坎", "兑", "艮", "离", "巽", "乾"};
        String upperTrigram = trigrams[upperNum - 1];
        String lowerTrigram = trigrams[lowerNum - 1];
        
        String hexagramName = getHexagramName(upperTrigram, lowerTrigram);
        String interpretation = generateInterpretation(question, "随机起卦", upperTrigram, lowerTrigram, changingYao, hexagramName);
        
        return new MeihuaResult(question, "随机起卦", upperTrigram, lowerTrigram, changingYao, hexagramName, interpretation);
    }
    
    private String getHexagramName(String upper, String lower) {
        String[] trigrams = {"坤", "震", "坎", "兑", "艮", "离", "巽", "乾"};
        int upperIndex = -1, lowerIndex = -1;
        
        for (int i = 0; i < trigrams.length; i++) {
            if (trigrams[i].equals(upper)) upperIndex = i;
            if (trigrams[i].equals(lower)) lowerIndex = i;
        }
        
        if (upperIndex >= 0 && lowerIndex >= 0 && upperIndex < 8 && lowerIndex < 8) {
            return HEXAGRAM_NAMES[upperIndex][lowerIndex];
        }
        
        return upper + lower + "卦";
    }
    
    private String generateInterpretation(String question, String method, String upper, String lower, int changingYao, String hexagramName) {
        StringBuilder interpretation = new StringBuilder();
        interpretation.append("【梅花易数完整解读】\n\n");
        interpretation.append("问题：").append(question).append("\n");
        interpretation.append("起卦方式：").append(method).append("\n");
        interpretation.append("卦象：").append(hexagramName).append("\n");
        interpretation.append("上卦：").append(upper).append("\n");
        interpretation.append("下卦：").append(lower).append("\n");
        interpretation.append("动爻：第").append(changingYao).append("爻\n\n");
        
        interpretation.append("【卦象分析】\n");
        interpretation.append("此卦显示了您当前的处境和发展趋势。\n");
        interpretation.append(upper).append("在上，代表外在环境和上层因素。\n");
        interpretation.append(lower).append("在下，代表内在状态和基础条件。\n");
        interpretation.append("第").append(changingYao).append("爻发动，表示变化的关键点。\n\n");
        
        interpretation.append("【综合建议】\n");
        interpretation.append("根据卦象显示，建议您保持积极的心态，顺应自然发展规律，在变化中寻找机会。");
        
        return interpretation.toString();
    }
    
    private void showMeihuaResult(final MeihuaResult result) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("梅花易数结果");
        builder.setMessage(result.interpretation);
        builder.setPositiveButton("确定", null);
        builder.setNegativeButton("保存结果", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                saveMeihuaResultToDatabase(result);
            }
        });
        builder.show();
    }
    
    private void saveMeihuaResultToDatabase(MeihuaResult result) {
        String hexagramData = result.upperTrigram + "," + result.lowerTrigram + "," + result.changingYao + "," + result.hexagramName;
        
        DivinationRecord record = new DivinationRecord(
            "meihua", 
            result.question,
            hexagramData,
            result.interpretation, 
            System.currentTimeMillis()
        );
        
        DatabaseManager.getInstance(this).saveRecord(record, new DatabaseManager.OnDataCallback<Long>() {
            public void onSuccess(Long id) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(MeihuaActivity.this, "梅花易数结果已保存", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            
            public void onError(Exception error) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(MeihuaActivity.this, "保存失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
